<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\Tree;
use app\api\helpers\v1\traits\FileUpload;
use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\AdminLog;
use app\api\model\v1\AuditExam;
use app\api\model\v1\AuditExamFile;
use app\api\model\v1\Exam;
use app\api\model\v1\ExamDetail;
use app\api\model\v1\ExamSign;
use app\api\model\v1\ExamStairType;
use app\api\model\v1\GiveBackExam;
use app\api\model\v1\NotUploadQuestion;
use app\api\model\v1\NotUploadQuestionLog;
use app\api\model\v1\SpecialAuditExam;
use app\api\model\v1\SpecialAuditExamFile;
use app\api\model\v1\SpecialAuditUser;
use app\api\model\v1\Unit;
use app\api\model\v1\Users;
use app\BaseController;
use think\facade\Db;
use think\facade\Env;
use think\facade\View;
use think\Request;
use think\Route;

class Audit extends BaseController
{
    use SearchDataForModel, FileUpload;

    /**
     * @User: 刘海龙1
     * @Date: 2021/10/11
     * @Time: 15:40
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 审核数据列表
     */
    public function getAuditExamList()
    {
        $limit = $this->request->param('limit', 10);
        //获取本身和下级单位单位的id
        if (!$this->is_super) {
            $childrenList =  $this->search->getChildrenIds($this->request->unit_id, true);
            $map[] = array('unit_id', 'in', $childrenList);
        } else {
            $map = [];
        }
        $where = [];
        if ($this->request->has('unit_s_id') && !empty($this->request->param('unit_s_id'))) {
            $unit_parent_arr = $this->request->param('unit_s_id');
            $children =  $this->search->getChildrenIds(intval(end($unit_parent_arr)), true);
            $where[] = ['unit_id', 'in', $children];
        }
        //        if ($this->request->has('date_of') && !empty($this->request->param('date_of'))) {
        //            $where[] = ['date_of', '=', $this->request->param('date_of')];
        //        }
        if ($this->request->has('user_id') && !empty($this->request->param('user_id'))) {
            $where[] = ['user_id', '=', $this->request->param('user_id')];
        }
        if ($this->request->has('attribute') && !empty($this->request->param('attribute'))) {
            $where[] = ['attribute', '=', $this->request->param('attribute')];
        }
        if ($this->request->has('status') && !empty($this->request->param('status'))) {
            $where[] = ['status', '=', $this->request->param('status')];
        }
        if ($this->request->has('date_range') && !empty($this->request->param('date_range'))) {
            $date_range = $this->request->param('date_range');
            $where[] = ['date_of', 'between', "$date_range[0],$date_range[1]"];
        }
        $res = AuditExam::with(['user', 'unit', 'exam', 'giveBack'])->where($map)->where($where)->order(['status' => 'asc', 'id' => 'desc'])->paginate($limit)->each(function ($item, $key) {
            $unit_parent =  $this->search->getParent($item['unit_id']);
            $item['unit_parent'] = reset($unit_parent)['unit_title'] ?? '未知';
            if ($item['attribute'] > 0) {
                $item['unit_attribute'] = Unit::$is_attribute[$item['attribute']];
            } else {
                $item['unit_attribute'] = '未知';
            }

            return $item;
        });
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/9/19 14:28
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 未上传数据源
     */
    public function getNotAuditExamList()
    {
        $limit = $this->request->param('limit', 10);
        $children =  $this->search->getChildrenIds($this->request->unit_id, true);
        $map[] = ['unit_id', 'in', $children];
        $where = [];
        if ($this->request->has('unit_s_id') && !empty($this->request->param('unit_s_id'))) {
            $unit_parent_arr = $this->request->param('unit_s_id');
            $children =  $this->search->getChildrenIds(intval(end($unit_parent_arr)), true);
            $where[] = ['unit_id', 'in', $children];
        }
        if ($this->request->has('user_id') && !empty($this->request->param('user_id'))) {
            $where[] = ['user_id', '=', $this->request->param('user_id')];
        }
        if ($this->request->has('status') && !empty($this->request->param('status'))) {
            if(intval($this->request->param('status')) == 1){
                $where[] = ['status', '=', 0];
            }else{
                $where[] = ['status', '=', $this->request->param('status')];
            }
        }
        if ($this->request->has('date_range') && !empty($this->request->param('date_range'))) {
            $date_range = $this->request->param('date_range');
            $where[] = ['create_time', 'between', "$date_range[0],$date_range[1]"];
        }
        $res =  NotUploadQuestion::with(['user', 'unit'])->where($map)->where($where)->paginate($limit)->each(function ($item, $key) {
            if (!is_null($item['img_json'])) {
                $item['img_arr'] = json_decode($item['img_json'], true);
            }
            $parent = $this->search->getParent($item['unit_id']);
            if($parent[0]['id'] === $this->request->unit_id){
                $item['is_flag'] = true;
            }else{
                $item['is_flag'] = false;
            }
            $item['username'] = $item['user']['username'];
            $item['unit_name'] = $item['unit']['unit_title'];
            return $item;
        });
        
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/9/19 14:28
     * @return \think\response\Json
     * 获取审核步骤 -- 审核
     */

    public function getStepLogList()
    {
        $id = $this->request->param('id');
      //  $q_id = $this->request->param('q_id');
        $res = NotUploadQuestion::findOrEmpty($id);
        if (!$res->isEmpty()) {
            $res->save(['status' => 2]); //结束
        }
        // $log = NotUploadQuestionLog::findOrEmpty($id);
        // if (!$log->isEmpty()) {

        //     $log->save(['status' => 1]); //结束
        //     if (!$res->isEmpty()) {
        //         $res->save(['status' => 2]); //结束
        //     }
        //     //$parent = $this->search->getParent($log->parent_unit_id);
        //     // if ($parent[0]['id'] !== 230) {
        //     //     NotUploadQuestionLog::create([
        //     //         'not_upload_question_id' => $log->not_upload_question_id,
        //     //         'parent_unit_id' => $parent[0]['id'],
        //     //         'status' => 0
        //     //     ]);
        //     //     if (!$res->isEmpty()){
        //     //         $res->save(['status' => 1]); //流程中
        //     //     }
        //     // }else{
        //     //     if (!$res->isEmpty()){
        //     //         $res->save(['status' => 2]); //结束
        //     //     }
        //     // }
        // }
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/9/19 15:41
     * @return \think\response\Json
     * 获取流程
     */
    public function getStep()
    {
        $q_id = $this->request->param('id');

        $log = NotUploadQuestionLog::with('unit')->where('not_upload_question_id', $q_id)->select()->toArray();
  
        return $this->response($log);
    }

    //平均分
    public function avgAuditExamScore()
    {
        //获取本身和下级单位单位的id
        if (!$this->is_super) {
            $childrenList =  $this->search->getChildrenIds($this->request->unit_id, true);
            $map[] = array('unit_id', 'in', $childrenList);
        } else {
            $map = [];
        }
        $where = [];
        if ($this->request->has('unit_s_id') && !empty($this->request->param('unit_s_id'))) {
            $unit_parent_arr = $this->request->param('unit_s_id');
            $children =  $this->search->getChildrenIds(intval(end($unit_parent_arr)), true);
            $where[] = ['unit_id', 'in', $children];
        }
        //        if ($this->request->has('date_of') && !empty($this->request->param('date_of'))) {
        //            $where[] = ['date_of', '=', $this->request->param('date_of')];
        //        }
        if ($this->request->has('user_id') && !empty($this->request->param('user_id'))) {
            $where[] = ['user_id', '=', $this->request->param('user_id')];
        }
        if ($this->request->has('attribute') && !empty($this->request->param('attribute'))) {
            $where[] = ['attribute', '=', $this->request->param('attribute')];
        }
        if ($this->request->has('status') && !empty($this->request->param('status'))) {
            $where[] = ['status', '=', $this->request->param('status')];
        }
        if ($this->request->has('date_range') && !empty($this->request->param('date_range'))) {
            $date_range = $this->request->param('date_range');
            $where[] = ['date_of', 'between', "$date_range[0],$date_range[1]"];
        }
        $sum = AuditExam::where($map)->where($where)->sum('final_score');
        $count = AuditExam::where($map)->where($where)->count();
        $avg = AuditExam::where($map)->where($where)->avg('final_score');
        $data = [
            'sum' => $sum,
            'count' => $count,
            'avg' => $avg
        ];
        return $this->response($data);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/11
     * @Time: 18:03
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 审核问卷
     */
    public function auditExam()
    {
        $id = $this->request->param('id', 0);
        $exam_id = $this->request->param('exam_id', 0);
        $audit = AuditExam::find($id);
        if (is_null($audit)) {
            return $this->response(403, "无法找到该记录");
        }
        $exam = Exam::find($exam_id);
        if (is_null($exam)) {
            return $this->response(403, "无法找到该问卷");
        }
        $user_id = $audit['user_id'];
        $res = ExamDetail::with(['examSecondLevel' => ['examStairType'], 'exam', 'auditExamFile' => function ($query) use ($id, $user_id) {
            $query->where(['audit_exam_id' => $id, 'user_id' => $user_id]);
            return $query;
        }])->where(['exam_id' => $exam_id])->select()->each(function ($item, $key) {
            $data = $item['auditExamFile'];
            if (!empty($data)) {
                $item['auditExamFile']['file_path_arr'] = json_decode($data['file_path'], true);
                if ($data['audit_way'] === 1) {
                    $item['show'] = "background: #2ADE1E;";
                } else if ($data['audit_way'] == 2) {

                    $item['show'] = "background: #F56C6C;";
                } else {
                    $item['show'] = "";
                }
            } else {
                $item['show'] = "background: #d9d327;";
            }
            return $item;
        })->toArray();
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/26
     * @Time: 16:19
     * @return \think\response\Json
     * 获取网点属性
     */
    public function getAttributeList()
    {
        $res = Unit::$is_attribute;
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/10/12
     * @Time: 8:54
     * @return \think\response\Json
     * 扣分
     */
    public function saveUltimatelyScore()
    {
        $data = $this->request->param();
        $type = $this->request->param('type', 0); //判断是通过还是扣分 默认为扣分
        if ($type === 1) {
            $data['ultimately_score'] = 0;
            $data['reason'] = null;
            $data['audit_way'] = 1;
        } else {
            $data['audit_way'] = 2;
        }
        $data['is_audit'] = 1;
        $res = AuditExamFile::update($data);
        AdminLog::record($type === 1 ? '通过模块' : '扣分模块', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/12
     * @Time: 15:30
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 微信端获取报告
     */
    public function getAuditExamUserList()
    {
        $limit = $this->request->param('limit', 10);
        $map[] = array('user_id', '=', $this->request->wx_id);
        $map[] = array('date_of', '=', $this->request->param('date_of'));
        $res = $this->search(new AuditExam(), $map, $limit, 'desc', ['user', 'unit', 'exam', 'admin']);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/12
     * @Time: 10:04
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 提交问卷
     */
    public function submitAuditExam()
    {
        $data = $this->request->param();
        $res = AuditExam::find($data['id']);
        if (is_null($res)) {
            return $this->response(403, '暂未找到该问卷记录');
        }
        $data['audit_admin_id'] = $this->request->uid;
        $data['audit_end_time'] = time();
        $data['status'] = 2; //已审核
        $res->save($data);
        AdminLog::record('正常审核提交', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/10/12
     * @Time: 11:07
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 完全符合
     */
    public function exactMatchAuditExam()
    {
        $data = $this->request->param();

        $res = AuditExam::find($data['id']);

        if (is_null($res)) {
            return $this->response(403, '暂未找到该问卷记录');
        }
        $data['audit_admin_id'] = $this->request->uid;
        $data['audit_end_time'] = time();
        //        $data['is_audit'] = 1;
        //        $data['audit_way'] = 1;
        $data['status'] = AuditExam::TWO_STATUS; //已审核
        $res->save($data);
        AuditExamFile::where(['audit_exam_id' => $data['id']])->update([
            'is_audit' => 1,
            'audit_way' => 1
        ]);
        AdminLog::record('完全符合提交按钮', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/12
     * @Time: 14:52
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 完全不符合
     */
    public function exactMatchDiscrepancy()
    {
        $data = $this->request->param();
        $auditExam = AuditExam::find($data['id']);
        if (is_null($auditExam)) {
            return $this->response(403, '暂未找到该问卷记录');
        }
        $res = AuditExamFile::with(['examDetail'])->where(['audit_exam_id' => $data['id'], 'exam_id' => $data['exam_id']])->select()->each(function ($item, $key) {
            if (!empty($item['file_path'])) {
                $item['file_path_count'] = count(json_decode($item['file_path'], true));
                return $item;
            }
        })->toArray();
        $original = 0; //原始分值
        $deduct_marks = 0; //最终扣分
        foreach ($res as $key => $v) {
            if (!empty($v['examDetail'])) {
                if ($data['way'] === 1) {
                    //系统扣分
                    $once = $v['file_path_count'] * $v['examDetail']['once_deduct_marks'];
                } else {
                    //手动扣分
                    $once = floatval($data['ultimately_score']);
                }
                $most = $v['examDetail']['most_deduct_marks'];
                $original += $v['examDetail']['most_deduct_marks']; //原始分值
            } else {
                $once = $v['file_path_count'] * 0;
                $most = 0;
                $original = 0;
            }
            //分值是否大于最大值
            if ($once > $most) {
                $ultimately_score = $most;
            } else {
                $ultimately_score = $once;
            }
            $deduct_marks += $ultimately_score; //最终扣分
            //更新数据表
            AuditExamFile::update([
                'id' => $v['id'],
                'ultimately_score' => $ultimately_score,
                'is_audit' => 2,
                'audit_way' => 2,
                'reason' => $data['reason'] === '' ? '系统扣分方式' : $data['reason'],
            ]);
        }
        $final_score = ($original - $deduct_marks) ?? 0; //最终得分
        $data['original'] = $original;
        $data['deduct_marks'] = $deduct_marks;
        $data['final_score'] = $final_score;
        $data['audit_admin_id'] = $this->request->uid;
        $data['audit_end_time'] = time();
        $data['status'] = AuditExam::TWO_STATUS; //已审核
        $data['audit_admin_id'] = $this->request->uid;
        $data['audit_end_time'] = time();
        $auditExam->save($data);
        AdminLog::record('完全不符合提交按钮', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/11
     * @Time: 15:34
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存问卷上传
     */
    public function saveAuditExam()
    {
        $data = $this->request->param();
        $data['user_id'] = $this->request->wx_id;
        $exam_id = intval($data['exam_id']);
        $date_of = $data['date_of'];
        $exam = Exam::find($exam_id);
        if (is_null($exam)) {
            return $this->response(403, '无法找到该问卷');
        }
        $user = Users::with(['unit'])->find($this->request->wx_id);
        if ($user['unit_id'] === 0) {
            $unit_id = $data['customUnitId'] ?? 0;
        } else {
            $unit_id = $user['unit_id'] ?? 0;
        }
        $data['unit_id'] = $unit_id;
        $data['industry_id'] = $user['industry_id'] ?? 0;
        $data['exam_creation_type'] = $exam['exam_creation_type'] ?? 0;
        $data['attribute'] = $exam['attribute'] ?? 0;
        $data['time'] = time();
        $redis_data_json = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $redis_key =  'audit_exam' . ':' . $date_of . ':' . $exam_id . ':' . $unit_id . ':' . $this->request->wx_id;
        $score = $data['detail_id'];
        $avc = $this->redis->ZRANGEBYSCORE($redis_key, $score, $score);
        if (!empty($avc)) {
            foreach ($avc as $key => $value) {
                $this->redis->ZREM($redis_key, $value);
            }
        }
        $this->redis->zadd($redis_key, $score, $redis_data_json);

        return $this->response();


        //        $res = AuditExam::where(['exam_id' => $exam_id, 'date_of' => $date_of,'unit_id'=>$unit_id,'user_id' => $this->request->wx_id])->find();
        //        if (is_null($res)) {
        //
        //


        //            //创建
        //            $audit_exam_id = AuditExam::create([
        //                'industry_id' => $user['industry_id'] ?? 0,
        //                'unit_id' => $unit_id,
        //                'user_id' => $this->request->wx_id,
        //                'exam_id' => $exam_id,
        //                'start_time' => time(),
        //                'exam_creation_type' => $exam['exam_creation_type'],
        //                'date_of' => $date_of,
        //                'attribute' => $exam['attribute'] ?? 0
        //            ])->id;
        //        } else {
        //            $audit_exam_id = $res['id'];
        //        }
        //        $file = AuditExamFile::where(['audit_exam_id' => $audit_exam_id, 'exam_detail_id' => $data['detail_id'], 'date_of' => $date_of,'unit_id'=>$unit_id, 'user_id' => $this->request->wx_id])->find();
        //        $data_file = [
        //            'audit_exam_id' => $audit_exam_id,
        //            'user_id' => $this->request->wx_id,
        //            'exam_id' => $exam_id,
        //            'unit_id' => $unit_id,
        //            'exam_stair_type_id' => $data['exam_stair_type_id'],
        //            'exam_second_level_id' => $data['exam_second_level_id'],
        //            'exam_detail_id' => $data['detail_id'],
        //            'file_path' => json_encode($data['img_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
        //            'content' => $data['content'] ?? '',
        //            'date_of' => $date_of,
        //            'attribute'=>$exam['attribute'] ?? 0
        //        ];
        //        if (!is_null($file)) {
        //            $file->save($data_file);
        //        } else {
        //            AuditExamFile::create($data_file);
        //        }
        //        return $this->response();
    }



    //    public function saveAuditExam()
    //    {
    //        $data = $this->request->param();
    //        $exam_id = intval($data['exam_id']);
    //        $date_of = $data['date_of'];
    //
    //        $exam = Exam::find($exam_id);
    //        if (is_null($exam)) {
    //            return $this->response(403, '无法找到该问卷');
    //        }
    //        $user = Users::with(['unit'])->find($this->request->wx_id);
    //        if ($user['unit_id'] === 0){
    //            $unit_id = $data['customUnitId'] ?? 0;
    //        }else{
    //            $unit_id = $user['unit_id'] ?? 0;
    //        }
    //        $res = AuditExam::where(['exam_id' => $exam_id, 'date_of' => $date_of,'unit_id'=>$unit_id,'user_id' => $this->request->wx_id])->find();
    //        if (is_null($res)) {
    //            //创建
    //            $audit_exam_id = AuditExam::create([
    //                'industry_id' => $user['industry_id'] ?? 0,
    //                'unit_id' => $unit_id,
    //                'user_id' => $this->request->wx_id,
    //                'exam_id' => $exam_id,
    //                'start_time' => time(),
    //                'exam_creation_type' => $exam['exam_creation_type'],
    //                'date_of' => $date_of,
    //                'attribute' => $exam['attribute'] ?? 0
    //            ])->id;
    //        } else {
    //            $audit_exam_id = $res['id'];
    //        }
    //        $file = AuditExamFile::where(['audit_exam_id' => $audit_exam_id, 'exam_detail_id' => $data['detail_id'], 'date_of' => $date_of,'unit_id'=>$unit_id, 'user_id' => $this->request->wx_id])->find();
    //        $data_file = [
    //            'audit_exam_id' => $audit_exam_id,
    //            'user_id' => $this->request->wx_id,
    //            'exam_id' => $exam_id,
    //            'unit_id' => $unit_id,
    //            'exam_stair_type_id' => $data['exam_stair_type_id'],
    //            'exam_second_level_id' => $data['exam_second_level_id'],
    //            'exam_detail_id' => $data['detail_id'],
    //            'file_path' => json_encode($data['img_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
    //            'content' => $data['content'] ?? '',
    //            'date_of' => $date_of,
    //            'attribute'=>$exam['attribute'] ?? 0
    //        ];
    //        if (!is_null($file)) {
    //            $file->save($data_file);
    //        } else {
    //            AuditExamFile::create($data_file);
    //        }
    //        return $this->response();
    //    }
    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 专项保存
     */
    public function saveZxAuditExam()
    {
        $data = $this->request->param();
        $exam_id = intval($data['exam_id']);
        $date_of = $data['date_of'];
        $exam = Exam::find($exam_id);
        if (is_null($exam)) {
            return $this->response(403, '无法找到该问卷');
        }
        $res = SpecialAuditExam::where(['exam_id' => $exam_id, 'date_of' => $date_of, 'unit_id' => $data['customUnitId']])->find();
        if (is_null($res)) {
            //创建
            $special_audit_exam_id = SpecialAuditExam::create([
                'industry_id' => $user['industry_id'] ?? 0,
                'unit_id' => $data['customUnitId'],
                //                'user_id' => $this->request->wx_id,
                'exam_id' => $exam_id,
                'start_time' => time(),
                'exam_creation_type' => $exam['exam_creation_type'],
                'date_of' => $date_of,
                'attribute' => $exam['attribute'] ?? 0
            ])->id;
        } else {
            $special_audit_exam_id = $res['id'];
        }
        //创建专项用户
        $is_user = SpecialAuditUser::where(['audit_exam_id' => $special_audit_exam_id, 'exam_id' => $exam_id, 'date_of' => $date_of, 'unit_id' => $data['customUnitId'], 'user_id' => $this->request->wx_id])->find();
        if (is_null($is_user)) {
            $special_audit_user_id = SpecialAuditUser::create([
                'audit_exam_id' => $special_audit_exam_id,
                'user_id' => $this->request->wx_id,
                'exam_id' => $exam_id,
                'unit_id' => $data['customUnitId'],
                'date_of' => $date_of,
            ])->id;
        } else {
            $special_audit_user_id = $is_user->id;
        }
        $files = SpecialAuditExamFile::where(['special_audit_exam_id' => $special_audit_exam_id, 'exam_detail_id' => $data['detail_id'], 'date_of' => $date_of, 'unit_id' => $data['customUnitId']])->select();
        //存在就删除 然后重新添加
        if (!$files->isEmpty()) {
            $files->delete(true);
        }
        //图片拆分保存
        foreach ($data['img_path'] as $key => $v) {
            $data_file = [
                'special_audit_exam_id' => $special_audit_exam_id,
                'user_id' => $v['uid'],
                'exam_id' => $exam_id,
                'unit_id' => $data['customUnitId'] ?? 0,
                'exam_stair_type_id' => $data['exam_stair_type_id'],
                'exam_second_level_id' => $data['exam_second_level_id'],
                'exam_detail_id' => $data['detail_id'],
                'file_path' => $v['img_path'],
                'content' => $data['content'] ?? '',
                'date_of' => $date_of,
                'attribute' => $exam['attribute'] ?? 0,
                'special_audit_user_id' => $special_audit_user_id
            ];
            SpecialAuditExamFile::create($data_file);
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/11
     * @Time: 14:05
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 检查是否查询了
     */
    public function checkAuditDetailIds()
    {
        $data = $this->request->param();
        if (intval($data['customUnitId']) === 0) {
            $unit_id = $this->user->unit_id;
        } else {
            $unit_id = $data['customUnitId'];
        }
        //,'user_id' => $this->request->wx_id
        $redis_key =  'audit_exam' . ':' . $data['date_of'] . ':' . intval($data['id']) . ':' . $unit_id . ':' . $this->request->wx_id;
        $new_data = [];
        if ($this->redis->has($redis_key)) {
            $aa = $this->redis->ZRANGE($redis_key, 0, -1, ['WITHSCORES' => true]);
            foreach ($aa as $key => $value) {
                $new_data[] = intval($value);
            }
        }
        $file = AuditExamFile::field('exam_detail_id')->where(['exam_id' => intval($data['id']), 'date_of' => $data['date_of'], 'unit_id' => $unit_id])->select()->toArray();
        foreach ($file as $key => $v) {
            $new_data[] = $v['exam_detail_id'];
        }
        if (!empty($new_data)) {
            return $this->response($new_data);
        } else {
            return $this->response(403, '暂无查询信息');
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 专项检查ids
     */
    public function checkAuditZxIds()
    {
        $data = $this->request->param();
        //,'user_id' => $this->request->wx_id
        $file = SpecialAuditExamFile::field('exam_detail_id')->where(['exam_id' => intval($data['id']), 'date_of' => $data['date_of'], 'unit_id' => $data['customUnitId']])->select()->toArray();

        $new_data = [];
        foreach ($file as $key => $v) {
            $new_data[] = $v['exam_detail_id'];
        }
        if (!empty($new_data)) {
            return $this->response($new_data);
        } else {
            return $this->response(403, '暂无查询信息');
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/11
     * @Time: 14:12
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取已经查询的
     */
    public function showAuditDetail()
    {
        $data = $this->request->param();
        if (intval($data['customUnitId']) === 0) {
            $unit_id = $this->user->unit_id;
        } else {
            $unit_id = $data['customUnitId'];
        }
        $redis_key =  'audit_exam' . ':' . $data['date_of'] . ':' . intval($data['id']) . ':' . $unit_id . ':' . $this->request->wx_id;
        $file_date = $this->findExamFile(intval($data['id']), $data['detail_id'], $data['date_of'], $this->request->wx_id, $unit_id);
        if ($this->redis->has($redis_key)) {
            $avc = $this->redis->ZRANGEBYSCORE($redis_key, $data['detail_id'], $data['detail_id']);
            if (!empty($avc)) {
                $abc = json_decode($avc[0], true);
                $abc['file_path'] = json_encode($abc['img_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                $abc['fileList'] = $abc['img_path'];
                return $this->response($abc);
            } else {
                if (!empty($file_date)) {
                    return $this->response($file_date);
                } else {
                    return json(['code' => 400, 'data' => []]);
                }
            }
        } else {
            $file_date = $this->findExamFile(intval($data['id']), $data['detail_id'], $data['date_of'], $this->request->wx_id, $unit_id);
            if (!empty($file_date)) {
                return $this->response($file_date);
            } else {
                return json(['code' => 400, 'data' => []]);
            }
        }


        //        $file = AuditExamFile::where(['exam_id' => intval($data['id']), 'exam_detail_id' => $data['detail_id'], 'date_of' => $data['date_of'], 'user_id' => $this->request->wx_id,'unit_id'=>$unit_id])->find();
        //        if (!is_null($file)) {
        //            $file['fileList'] = json_decode($file['file_path'], true);
        //            return $this->response($file->toArray());
        //        } else {
        //            return json(['code' => 400, 'data' => []]);
        //        }
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/7/25 11:22
     * @param $exam_id
     * @param $detail_id
     * @param $date_of
     * @param $user_id
     * @param $unit_id
     * @return array
     * 找文件图片
     */
    public function findExamFile($exam_id, $detail_id, $date_of, $user_id, $unit_id)
    {
        $file = AuditExamFile::where(['exam_id' => $exam_id, 'exam_detail_id' => $detail_id, 'date_of' => $date_of, 'user_id' => $user_id, 'unit_id' => $unit_id])->findOrEmpty();
        $new_data = [];
        if (!$file->isEmpty()) {
            $file['fileList'] = json_decode($file['file_path'], true);
            $new_data = $file->toArray();
        }
        return $new_data;
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 专项检查显示
     */
    public function showAuditDetailZx()
    {
        $data = $this->request->param();
        if (intval($data['customUnitId']) === 0) {
            $unit_id = $this->user->unit_id;
        } else {
            $unit_id = $data['customUnitId'];
        }
        $files = SpecialAuditExamFile::where(['exam_id' => intval($data['id']), 'exam_detail_id' => $data['detail_id'], 'date_of' => $data['date_of'], 'unit_id' => $unit_id])->select();
        $new_arr = [];
        $arr_img = [];
        $content = '';
        if (!$files->isEmpty()) {
            foreach ($files as $key => $v) {
                $new_arr[$key]['id'] = $v['id'];
                $new_arr[$key]['url'] = $v['file_path'];
                $new_arr[$key]['name'] = '小程序';
                $new_arr[$key]['uid'] = $v['user_id'];
                $new_arr[$key]['img_path'] = $v['file_path'];
                $arr_img[$key] = $v['file_path'];
                $content = $v['content'];
            }
            //            $file['fileList'] = json_decode($file['file_path'], true);
            return $this->response(['fileList' => $new_arr, 'arr_img' => $arr_img, 'content' => $content]);
        } else {
            return json(['code' => 400, 'data' => []]);
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/30
     * @Time: 16:22
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 问卷显示
     */
    public function getExamQuestionInfo()
    {
        $week = date('w'); //周几
        //  $env_week = Env::get('WEEK.week', 'WEEK.default_week');
        $data = $this->request->param();
        $map = [];
        if ($this->user->unit_id == 230) {
            $unit_id = 0;
        } else {
            $unit_id = $this->user->unit_id;
        }
        if (!empty($this->user)) {
            $childrenList = $this->search->getParentsIds($unit_id, true);
            if ($unit_id !== 0) {
                $map[] = array('attribute', '<>', 3);
                $map[] = array('attribute', '=', $this->user->unit->attribute);
                $map[] = array('unit_id', 'in', $childrenList);
                $map[] = array('is_ident', '=', intval($this->user->is_ident));
                $map[] = ['', 'EXP', Db::raw("FIND_IN_SET($week,is_week)")];
            } else {
                $map[] = array('attribute', '<>', 3);
            }
        }
        $date_of = $data['date_of']; //日期
        $map[] = array('is_release', '=', 1);
        //        if (intval($week) === intval($env_week)){
        //            $map[] = array('is_week', '=', intval($env_week));
        //        }else{
        //            $map[] = array('is_week', '<>', intval($env_week));
        //        }
        $exam = Exam::with(['admin', 'examAudit' => function ($q) use ($date_of) {
            $q->with(['giveBack'])->where(['date_of' => $date_of, 'user_id' => $this->request->wx_id]); //条件为当天并且找到对应的用户，以及已经审核
            return $q;
        }])->where($map)->withCount(['examDetail', 'examAudit' => function ($query) use ($date_of) {
            $query->where('date_of', '=', $date_of);
            return $query;
        }])->select()->each(function ($item, $key) {
            if (!empty($item['examAudit']->toArray())) {
                foreach ($item['examAudit'] as $k => $v) {
                    if (!empty($v['giveBack'])) {
                        $item['back_content'] = $v['giveBack']['back_content'] ?? '';
                    } else {
                        $item['back_content'] = '';
                    }
                    if ($v['status'] === 1) {
                        $item['is_audit'] = 1; //答题未审核
                    } else if ($v['status'] === 2) {
                        $item['is_audit'] = 2; //答题并且审核
                    } else if ($v['status'] === 3) {
                        $item['is_audit'] = 3; //答题并且拒绝
                    } else {
                        $item['is_audit'] = 5; //未知
                    }
                }
            } else {
                $item['is_audit'] = 5; // 未答题
            }
            $item['exam_creation_type_name'] = Exam::$exam_creation_type[$item['exam_creation_type']] ?? '';
            $item['exam_type_name'] = Exam::$is_exam_type[$item['exam_type']] ?? '';
            return $item;
        })->toArray();
        if (empty($exam)) {
            return $this->response(403, '空数据');
        } else {
            return $this->response($exam);
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/23
     * @Time: 13:25
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 专项
     */
    public function getExamZxs()
    {
        $data = $this->request->param();
        if ($this->user->unit_id == 230) {
            $unit_id = 0;
        } else {
            $unit_id = $this->user->unit_id;
        }

        if (!empty($this->user)) {
            $childrenList = $this->search->getParentsIds($unit_id, true);
            if ($unit_id !== 0) {
                $map[] = array('attribute', '=', 3);
                $map[] = array('attribute', '=', $this->user->unit->attribute);
                $map[] = array('unit_id', 'in', $childrenList);
            } else {
                $map[] = array('attribute', '=', 3);
            }
        }
        $date_of = $data['date_of']; //日期
        $map[] = array('is_release', '=', 1);
        //, 'examAudit' => function ($q) use ($date_of) {
        //            $q->where(['date_of' => $date_of, 'user_id' => $this->request->wx_id]); //条件为当天并且找到对应的用户，以及已经审核
        //            return $q;
        //        },
        $exam = Exam::with(['admin', 'specialAuditUser' => function ($a) use ($date_of) {
            $a->where(['date_of' => $date_of, 'user_id' => $this->request->wx_id]); //条件为当天并且找到对应的用户，以及已经审核
            return $a;
        }])->where($map)->withCount(['examDetail', 'specialAuditUser' => function ($query) use ($date_of) {
            $query->where('date_of', '=', $date_of);
        }])->select()->each(function ($item, $key) {
            //            if (!empty($item['examAudit']->toArray())) {
            //                foreach ($item['examAudit'] as $k => $v) {
            //                    if ($v['status'] === 1) {
            //                        $item['is_audit'] = 1; //答题未审核
            //                    } else {
            //                        $item['is_audit'] = 2; //答题并且审核
            //                    }
            //                }
            //            } else {
            //                $item['is_audit'] = 3; // 未答题
            //            }
            //判断专项是否上传
            if (!empty($item['specialAuditUser']->toArray())) {
                $item['is_user'] = 1; // 已答题
            } else {
                $item['is_user'] = 2; // 未答题
            }
            $item['exam_creation_type_name'] = Exam::$exam_creation_type[$item['exam_creation_type']] ?? '';
            $item['exam_type_name'] = Exam::$is_exam_type[$item['exam_type']] ?? '';
            return $item;
        })->toArray();
        if (empty($exam)) {
            return $this->response(403, '空数据');
        } else {
            return $this->response($exam);
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/30
     * @Time: 16:53
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据问卷id 获取详情
     */
    public function getExamDetail()
    {
        $exam_id = $this->request->param('id');
        $exam = ExamStairType::with(['examSecondLevel' => ['examDetail']])->where(['exam_id' => $exam_id])->select()->toArray();
        return $this->response($exam);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/11
     * @Time: 10:09
     * @return \think\response\Json
     * 上传图片
     */
    public function UploadImg()
    {
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $result = $this->save($file, 'exam_img');
        return $this->response($result);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/13
     * @Time: 11:56
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取问卷报告信息
     */
    public function getReportDetail()
    {
        $id = $this->request->param('id');
        $res = AuditExam::with(['unit', 'exam' => ['examDetail', 'examStairType' => ['examFile.examDetail' => function ($q) use ($id) {
            $map[] = array('audit_exam_id', '=', $id);
            $map[] = array('audit_way', '=', 2);
            $q->where($map); //扣分
            return $q;
        }]], 'examFile.examDetail' => function ($query) use ($id) {
            $map[] = array('audit_exam_id', '=', $id);
            $map[] = array('audit_way', '=', 2);
            $query->where($map); //扣分
            return $query;
        }])->withCount(['examFile'])->find(intval($id));
        if (is_null($res)) {
            return $this->response(403, '无法找到该问卷');
        }
        if (!empty($res['exam']['examDetail'])) {
            $res['count'] = count($res['exam']['examDetail']); //总数量
        } else {
            $res['count'] = 0; //总数量
        }
        $res['error_count'] = count($res['examFile']); //扣分数量
        $res['tg_count'] = ($res['exam_file_count'] - count($res['examFile'])); //通过数量
        $res['not_upload_count'] = ($res['count'] - $res['exam_file_count']); //未上传数量
        $da = $res['exam']['examStairType']->toArray();
        if (!empty($da)) {
            foreach ($da as $k => $v) {
                if (!empty($v['examFile'])) {
                    $da[$k]['count_type'] = count($v['examFile']) ?? 0;
                } else {
                    $da[$k]['count_type'] = 0;
                }
            }
        }
        $res['examStairType'] = $da; //二级指标
        return $this->response($res->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/10/29
     * @Time: 15:32
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 检查问卷是否呗审核 $this->request->wx_id
     */
    public function checkUploadExamFile()
    {
        $mid = $this->request->param('mid');
        $date_of = $this->request->param('date_of');
        $res = AuditExam::where(['exam_id' => $mid, 'date_of' => $date_of, 'user_id' => $this->request->wx_id, 'status' => 2])->find();
        if (!empty($res)) {
            return $this->response(403, '该问卷已经审核过,您无法再次补录');
        } else {
            return $this->response();
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/4
     * @Time: 14:14
     * @return \think\response\Json
     * 返回新增自定义的id
     */
    public function customAddUnit()
    {
        $data = $this->request->param();
        $data['pid'] = 167; //自定义父级id
        $data['create_id'] = $this->request->wx_id;
        $data['industry_id'] = 1; //行业 邮政
        $data['level'] = 2; //等级
        $data['attribute'] = 3; //网点属性 默认为3 //专项
        $res = Unit::where(['unit_title' => $data['unit_title']])->find();
        if (!is_null($res)) {
            $unit_id = $res->id;
        } else {
            $unit_id = Unit::create($data)->id;
        }
        return $this->response(['unit_id' => $unit_id]);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/11/4
     * @Time: 16:37
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存签名
     */
    public function saveSign()
    {
        $data = $this->request->param();
        $data['sign_path'] = json_encode($data['sign_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $res = ExamSign::where(['audit_exam_id' => $data['audit_exam_id']])->find();
        if (!is_null($res)) {
            $res->save($data);
        } else {
            ExamSign::create($data);
        }
        return $this->response();
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取专项的单位列表
     */
    public function getZxUnitList()
    {
        $res = Unit::where(['attribute' => 3, 'level' => 3])->order('create_time desc')->select();
        return $this->response($res);
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除专项图片
     */
    public function delImgZx()
    {
        $data = $this->request->param();
        $res = AuditExamFile::find($data['id']);
        if (!is_null($res)) {
            $path_arr = json_decode($res['file_path'], true);
            foreach ($path_arr as $key => $value) {
                if ($value['img_path'] == $data['path'][0]) {
                    if ($this->request->wx_id == $value['uid']) {
                        return $this->response();
                    } else {
                        return json(['code' => 405, 'data' => $path_arr]);
                    }
                }
            }
        } else {
            return $this->response(403, '未知问题');
        }
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/7/15 15:38
     * @return \think\response\Json
     * 问卷审核时退回操作
     */
    public function giveBackExam()
    {
        $data = $this->request->param();
        $is_find = AuditExam::findOrEmpty($data['id']);
        if ($is_find->isEmpty()) {
            return $this->response(403, '此问卷不存在');
        }
        if ($is_find->status !== AuditExam::ONE_STATUS) {
            return $this->response(403, '该问卷已审核，请勿重复审核');
        }
        //新增的到退回表中
        $give_back_id =  GiveBackExam::create([
            'audit_exam_id' => $data['id'],
            'exam_id' => $data['exam_id'],
            'back_content' => $data['back_content'],
            'exercise_user_id' => $this->request->uid
        ])->id;
        if ($give_back_id > 0) {
            //更新问卷审核表状态
            $is_find->save([
                'status' => AuditExam::THREE_STATUS
            ]);
            //操作日志
            AdminLog::record('点击退回按钮', [
                'audit_exam_id' => $data['id'],
                'exam_id' => $data['exam_id'],
                'back_content' => $data['back_content'],
            ], $this->request->uid, $this->request->username);
        }
        return $this->response();
    }
}
